package com.li.blog.service.impl;

import com.alibaba.fastjson.JSON;
import com.li.blog.dao.pojo.SysUser;
import com.li.blog.service.LoginService;
import com.li.blog.service.SysUserService;
import com.li.blog.utils.JWTUtils;
import com.li.blog.vo.ErrorCode;
import com.li.blog.vo.Result;
import com.li.blog.vo.params.LoginParam;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;
import java.util.concurrent.TimeUnit;


@Service
@Transactional
public class LoginServiceImpl implements LoginService {

  @Autowired
  private SysUserService sysUserService;
  @Autowired
  private RedisTemplate<String, String> redisTemplate;

  private static final String slat = "Ljcblog!@#";


  @Override
  public Result login(LoginParam loginParam) {
    /**
     * 1 检查参数是否合理
     * 2 根据用户民和密码在表中查询 是否存在
     * 3 不存在提示 用户名密码有误
     * 4 存在且密码正确成功登录 存入takon返回给前端
     * 5 takon存入redis中 设置过期的时间
     * 登录认证先认证takeon是否合法 然后认证redis是否存在
     */
    String account = loginParam.getAccount();
    String password = loginParam.getPassword();

    //判断是否为空 为空的话返回参数有误
    if (StringUtils.isBlank(account) || StringUtils.isBlank(password)) {
      return Result.fail(ErrorCode.PARAMS_ERROR.getCode(), ErrorCode.PARAMS_ERROR.getMsg());
    }
    //调用service 通过用户名密码查询
    // 判断是否为空 为空就返回
    //在数据库中密码加密所以需要提前进行加密
    password = DigestUtils.md5Hex(password + slat);
    SysUser sysUser = sysUserService.findUser(account, password);

    if (sysUser == null) {
      return Result.fail(ErrorCode.ACCOUNT_PWD_NOT_EXIST.getCode(), ErrorCode.ACCOUNT_PWD_NOT_EXIST.getMsg());
    }

    //根据id创建token然后丢入redis中
    String token = JWTUtils.createToken(sysUser.getId());
    redisTemplate.opsForValue().set("TOKEN_" + token, JSON.toJSONString(sysUser), 1, TimeUnit.DAYS);
    return Result.success(token);
  }

  @Override
  public SysUser checkToken(String token) {
    /**
     * 检查是否为空
     * 检查是否合理
     * 在redis中检查是否存在
     * 将json转为sysuser对象
     */
    if (StringUtils.isBlank(token)) {
      return null;
    }
    Map<String, Object> stringObjectMap = JWTUtils.checkToken(token);
    if (stringObjectMap == null) {
      return null;
    }
    String userJson = redisTemplate.opsForValue().get("TOKEN_" + token);
    if (StringUtils.isBlank(userJson)) {
      return null;
    }
    SysUser sysUser = JSON.parseObject(userJson, SysUser.class);
    return sysUser;
  }

  @Override
  public Result logout(String token) {
    redisTemplate.delete("TOKEN_"+token);
    return Result.success(null);
  }

  @Override
  public Result resgister(LoginParam loginParam) {
    /**
     * 判断loginParam是否合法
     * 判断是否存在
     * 存在返回 已经注册
     * 不存在 进行注册 然后生成token存入redis 直接登录
     * 注意加入事务一有问题进行回滚
     */

    String account = loginParam.getAccount();
    String password = loginParam.getPassword();
    String nickname = loginParam.getNickname();

    //业务判空
    if (StringUtils.isBlank(account)
            || StringUtils.isBlank(password)
            || StringUtils.isBlank(nickname)
    ){
      //错误退出
      return Result.fail(ErrorCode.PARAMS_ERROR.getCode(),ErrorCode.PARAMS_ERROR.getMsg());
    }

    //是否用户名重复
    SysUser sysUser = sysUserService.findUserByAccount(account);
    if (sysUser != null){
      return Result.fail(ErrorCode.ACCOUNT_EXIST.getCode(),ErrorCode.ACCOUNT_EXIST.getMsg());
    }
    //设置默认值
    sysUser = new SysUser();
    sysUser.setNickname(nickname);
    sysUser.setAccount(account);
    sysUser.setPassword(DigestUtils.md5Hex(password+slat));
    sysUser.setCreateDate(System.currentTimeMillis());
    sysUser.setLastLogin(System.currentTimeMillis());
    sysUser.setAvatar("/static/img/logo.b3a48c0.png");
    sysUser.setAdmin(1); //1 为true
    sysUser.setDeleted(0); // 0 为false
    sysUser.setSalt("");
    sysUser.setStatus("");
    sysUser.setEmail("");
    this.sysUserService.save(sysUser);

    String token = JWTUtils.createToken(sysUser.getId());

    redisTemplate.opsForValue().set("TOKEN_"+token, JSON.toJSONString(sysUser),1, TimeUnit.DAYS);

    return Result.success(token);
  }
}
